package Excesser.Demoone;


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

//赫夫曼树练习
public class TestNode {
    public static void main(String[] args) {


        int[] array = {20, 17, 12, 6, 5, 33, 24};
        Node root = createHuffmanTree(array);
        preOrder(root);
    }


    public static Node createHuffmanTree(int[] arrays) {

        List<Node> huffmannode = new ArrayList<>();

        //将数组转化为结点
        for (int i : arrays) {
            huffmannode.add(new Node(i));
        }

        while (huffmannode.size() > 1) {
            Collections.sort(huffmannode);
            System.out.println("集合元素：" + huffmannode);
            Node leftnode = huffmannode.get(0);
            Node rightnode = huffmannode.get(1);

            Node root = new Node(leftnode.value + rightnode.value);

            root.left = leftnode;
            root.right = rightnode;

            huffmannode.remove(leftnode);
            huffmannode.remove(rightnode);

            huffmannode.add(root);

        }

        return huffmannode.get(0);
    }

    //前序遍历

    public static void preOrder(Node root) {
        if (root != null) {
            root.preOrder();
        } else {
            System.out.println("空数，无法遍历。。。");
        }
    }
}
